import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-08-15
 * Time: 14:39
 * To BE A Better Person-2020-3-2
 */
//描述一次任务
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable,long time){
        this.runnable=runnable;
        //记录要开始的时间
        this.time=System.currentTimeMillis()+time;
    }

    public long getTime() {
        return time;
    }

    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time-o.time);
    }
}


class MyTimer{
    private Object locker=new Object();

    private PriorityBlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long time){
        MyTask myTask=new MyTask(runnable,time);
        synchronized (locker){
            queue.put(myTask);
            locker.notify();
        }


    }
    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                try {
                    synchronized (locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTask temp=queue.take();
                        //判断当前时间与队首时间的大小
                        if(temp.getTime()>System.currentTimeMillis()){
                            queue.put(temp);
                            locker.wait(temp.getTime()-System.currentTimeMillis());
                        }else{
                            temp.run();
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }


}


public class TestDemo {
    public static void main(String[] args) {
        MyTimer timer=new MyTimer();
        timer.schedule(()->{

                System.out.println("1111");

        },1000);
        timer.schedule(()->{

                System.out.println("2222");

        },2000);
        timer.schedule(()->{

                System.out.println("3333");

        },3000);
    }
}
